package com.fjwt.gz.mch.ctrl.fans;

import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.aop.MethodLog;
import com.fjwt.gz.core.constants.CS;
import com.fjwt.gz.core.model.ApiRes;
import com.fjwt.gz.db.dto.FansActivityDTO;
import com.fjwt.gz.db.entity.FansEntity;
import com.fjwt.gz.db.entity.FansUserEntity;
import com.fjwt.gz.db.entity.SysConfig;
import com.fjwt.gz.db.vo.FansActivityVO;
import com.fjwt.gz.db.vo.InviterRecordVO;
import com.fjwt.gz.mch.config.SystemYmlConfig;
import com.fjwt.gz.mch.ctrl.CommonCtrl;
import com.fjwt.gz.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 小程序会员个人中心接口
 */
@Slf4j
@RestController
@RequestMapping("/api/fans")
public class FansController extends CommonCtrl {


    @Value("${province.code}")
    private String provinceCode;
    @Value("${payConfig.appid}")
    private String APPID;
    @Value("${payConfig.appSecret}")
    private String APPSECRET;

    @Autowired
    protected FansUserService fansUserService;
    @Autowired
    private FansService fansService;
    @Autowired
    private SystemYmlConfig systemYmlConfig;
    @Autowired
    protected AgentInfoService agentInfoService;
    @Autowired
    protected FansMchService fansMchService;
    @Autowired
    protected AgentAppService agentAppService;
    @Autowired
    protected AssetMonthService assetMonthService;
    @Autowired
    protected AssetQuarterService assetQuarterService;
    @Autowired
    protected FansAuthService fansAuthService;
    @Autowired
    private InviterRecordService inviterRecordService;

    @Value("${environment.code}")
    private boolean environment;

    /**
     * 获取一鑫支付公众号openid
     *
     * @return
     */
    @PostMapping("/getWxchatPayOpenid")
    public ApiRes getWxchatPayOpenid() {
        // 标记
        String code = getValString("code");
        AES aes = new AES(CS.DB_KEY.getBytes());
        String appId = aes.decryptStr(APPID);
        String secret = aes.decryptStr(APPSECRET);
        String locationAgentNo = request.getHeader("locationAgentNo");
        // 通过转介进来的商户号
        log.info("获取一鑫支付公众号openid，请求地址：/api/fans/getWxchatPayOpenid，请求参数：code：{}，appId：{}，secret：{}", code, appId, secret);
        FansEntity wxchatPayOpenid = fansService.getWxchatPayOpenid(appId, secret,code, environment, locationAgentNo);
        FansEntity data = new FansEntity();
        BeanUtils.copyProperties(wxchatPayOpenid, data);
        return ApiRes.ok(data);
    }


    /**
     * 登录小程序并获取地域小程序的openid
     */
    @PostMapping("/getPlaceWxchatOpenid")
    public ApiRes getPlaceWxchatOpenid() {
        log.info("获取地域小程序用户的openid");

        String payOpenid = getValString("payOpenId");
        String code = getValString("wxcode");
        String appId = request.getHeader("appid");
        Long fansId = getValLong("fansId");
        String inviterInfo = getValString("inviterInfo");
        Integer inviterType = getValInteger("inviterType");
        String locationAgentNo = request.getHeader("locationAgentNo");
        String jwtSecret = systemYmlConfig.getJwtSecret();
        JSONObject placeWxchatOpenid = fansService.getPlaceWxchatOpenid(payOpenid, appId, code, inviterInfo, inviterType, fansId, jwtSecret, locationAgentNo);
        return ApiRes.ok(placeWxchatOpenid);
    }

    /**
     * 个人详情信息
     */
    @PostMapping("/detail")
    public ApiRes getFansDetail() {
        Long fansId = getCurrentUser().getFansId();
        Long userId = getCurrentUser().getUserId();
        String appid = getCurrentUser().getAppId();
        String locationAgentNo = request.getHeader("locationAgentNo");
        log.info("C端用户个人详情接口调用：请求地址：/api/fans/detail，请求参数：用户fansId:{}，appid:{}，userId：{}，agentNo：{}", fansId, appid, userId, locationAgentNo);
        Map<String, Object> fansDetail = fansService.getFansDetail(fansId, userId, appid, locationAgentNo);
        Map<String, Object> map = Map.copyOf(fansDetail);
        return ApiRes.ok(map);
    }

    /**
     * 用户绑定机构网点
     */
    @PostMapping("/findFansBindAgent")
    public ApiRes findFansBindAgent() {
        Long fansId = getCurrentUser().getFansId();
        String lng = getValString("lng");
        String lat = getValString("lat");
        String appId = request.getHeader("appid");
        String locationAgentNo =request.getHeader("locationAgentNo");
        JSONObject fansBindAgent = fansService.findFansBindAgent(lng, lat, fansId, appId, locationAgentNo);
        return ApiRes.ok(fansBindAgent);
    }

    /**
     * 登录选择机构接口
     * @return
     */
    @PostMapping("/fansBindAgent")
    public ApiRes fansBindAgent() {
        Long fansId = getCurrentUser().getFansId();
        String agentNo = getValString("agentNo");
        String appId = request.getHeader("appid");
        log.info("C端用户绑定机构网点接口调用：请求地址：/api/fans/fansBindAgent，请求参数：用户fansId:{}，agentNo:{}，appId{}", fansId, agentNo, appId);
        return fansService.insertFansEntity(fansId, agentNo, appId);
    }


    @PostMapping("/getuserphonenumber")
    public ApiRes getuserphonenumber() {
        Long fansId = getCurrentUser().getFansId();
        String code = getValString("code");
        String appId = request.getHeader("appid");
        Long userId = getCurrentUser().getUserId();
        String locationAgentNo = request.getHeader("locationAgentNo");
        FansEntity getuserphonenumber = fansService.getuserphonenumber(fansId, code, appId, userId, locationAgentNo);
        return ApiRes.ok(getuserphonenumber);
    }


    /**
     * 会员管理-参与活动列表查询
     */
    @PostMapping("/activityList")
    public ApiRes getFansActivity() {
        FansActivityDTO fansActivityDTO = getObject(FansActivityDTO.class);
        log.info("C端会员管理-参与活动列表查询，请求地址：/api/fans/activityList，请求参数：{}", JSONObject.toJSONString(fansActivityDTO));
        IPage<FansActivityVO> page = fansService.getFansActivity(getIPage(), fansActivityDTO);
        log.info("C端会员管理-参与活动列表查询，请求地址：/api/fans/activityList，返回结果：{}", JSONObject.toJSONString(page));
        return ApiRes.page(page);
    }

    @PostMapping("/getCodePlaceOpenid")
    public ApiRes getChangChunPlaceOpenid() {
        String locationAgentNo = request.getHeader("locationAgentNo");
        Long fansId = getCurrentUser().getFansId();
        String appid = getValString("officialAppId");
        String code = getValString("code");
        log.info("请求地址：/api/fans/getCodePlaceOpenid，请求参数：code：{},appId：{}，fansId：{}", code, appid, fansId);
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getConfigKey, appid);
        SysConfig sysConfig = sysConfigService.getOne(wrapper);
        FansUserEntity changChunPlaceOpenid = fansService.getChangChunPlaceOpenid(code, appid, fansId, sysConfig,locationAgentNo);
        FansUserEntity data = new FansUserEntity();
        BeanUtils.copyProperties(changChunPlaceOpenid, data);
        return ApiRes.ok(data);
    }

//    /**
//     * 用户绑定商户
//     */
//    @PostMapping("/fansBindMch")
//    public ApiRes fansBindMch() {
//        Long fansId = getCurrentUser().getFansId();
//        String mchNo = getValString("mchNo");
//        if (Objects.isNull(fansId) || StringUtils.isEmpty(mchNo)) {
//            throw new BizException("网络故障，请稍后重试！");
//        }
//        log.info("用户绑定商户信息：请求地址：/api/fans/fansBindMch，请求参数：用户fansId：{}，商户号：{}", fansId, mchNo);
//        //根据商户号查询是否已经添加过了
//        LambdaQueryWrapper<FansMchEntity> fansMchEntityLambdaQueryWrapper = FansMchEntity.gw();
//        fansMchEntityLambdaQueryWrapper.eq(FansMchEntity::getFansId, fansId);
//        fansMchEntityLambdaQueryWrapper.eq(FansMchEntity::getMchNo, mchNo);
//        List<FansMchEntity> fansMchEntities = fansMchService.list(fansMchEntityLambdaQueryWrapper);
//        if (fansMchEntities != null && fansMchEntities.size() > 0) {
//            throw new BizException("此商户号已被绑定");
//        }
//        log.info("用户绑定商户信息：请求地址：/api/fans/fansBindMch，用户fansId：{}，商户号：{}", fansId, mchNo);
//        FansMchEntity fansMchEntity = new FansMchEntity();
//        fansMchEntity.setFansId(fansId);
//        fansMchEntity.setMchNo(mchNo);
//        fansMchService.save(fansMchEntity);
//
//        // 绑定商户号后删除token缓存
//        String cacheKey = CS.getCacheKeyToken(CS.SYS_ROLE_TYPE.FANS, fansId, String.valueOf(getCurrentUser().getUserId()));
//        RedisUtil.del(cacheKey);
//
//        return ApiRes.ok();
//    }

    /**
     * 小程序用户注销功能
     *
     * @return
     */
    @MethodLog(remark = "小程序用户注销功能")
    @PostMapping("/delFanUser")
    public ApiRes delFanUser() {
        Integer state = getValInteger("state");
        String phone = getValString("phone");
        String code = getValString("smsCode");
        Long userId = getCurrentUser().getUserId();
        return fansService.delFanUser(state, phone, code, userId) ? ApiRes.ok() : ApiRes.customFail("操作失败！");
    }

    /**
     * 接受邀请转介
     */
    @PostMapping("/inviterConfirmAward")
    public ApiRes inviterConfirmAward() {
        String time = getValString("time");
        Long userId = getCurrentUser().getUserId();
        String appId = getCurrentUser().getAppId();
        String agentNo = getCurrentUser().getAgentNo();
        Long inviterId = getValLong("inviterId");
        if (null == inviterId || null == userId || null == appId || null == agentNo) {
            return ApiRes.customFail("网络故障，请稍后重试");
        }
        log.info("接受邀请转介，请求地址：/api/fans/inviterConfirmAward，请求参数：time：{},userId：{},inviterId：{},appId：{},agentNo：{}", time, userId, inviterId, appId, agentNo);
        ApiRes res = fansService.inviterConfirmAward(time, inviterId, userId, appId, agentNo);
        return new ApiRes(res.getCode(),res.getMsg(),res.getData(),null,null);
    }

    /**
     * 福分拉新记录
     *
     * @return
     */
    @PostMapping("/getInviterList")
    public ApiRes getInviterList() {
        Long fansId = getCurrentUser().getFansId();
        if (null == fansId) {
            return ApiRes.customFail("网络故障，请稍后重试！");
        }
        log.info("c端福分拉新记录，请求地址：/api/fans/getInviterList，请求参数：fansId：{}", fansId);
        IPage<InviterRecordVO> page = inviterRecordService.findUserInviterList(getIPage(), fansId);
        log.info("c端福分拉新记录，请求地址：/api/fans/getInviterList，返回结果：{}", JSONObject.toJSONString(page));
        return ApiRes.page(page);
    }

    /**
     * 福分、待使用福券、未核销奖品数量
     **/
    @PostMapping("/scoreOrcouponCount")
    public ApiRes getScoreOrcouponCount() {
        Long fansId = getCurrentUser().getFansId();
        String appId = getCurrentUser().getAppId();
        log.info("c端福分、待使用福券、未核销奖品数量，请求地址：/api/fans/scoreOrcouponCount，请求参数：fansId：{}, appId:{}", fansId, appId);
        JSONObject json = fansService.getScoreOrcouponCount(fansId, appId);
        log.info("c端福分、待使用福券、未核销奖品数量，请求地址：/api/fans/scoreOrcouponCount，返回结果：{}", JSONObject.toJSONString(json));
        return ApiRes.ok(json);
    }

    @PostMapping("/userExit")
    public ApiRes userExit() {
        Long userId = getCurrentUser().getUserId();
        Long fansId = getCurrentUser().getFansId();
        log.info("C端用户退出登录，请求地址：/api/fans/userExit，请求参数：fansId：{}", fansId);
        return fansService.userExit(fansId,userId) ? ApiRes.ok() : ApiRes.customFail("退出失败！");
    }


    /**
     * 编辑个人信息
     */
    @PostMapping("/update")
    public ApiRes update() {
        FansEntity object = getObject(FansEntity.class);
        log.info("C端用户修改个人信息，请求地址：/api/fans/update，请求参数：{}", JSON.toJSONString(object));
        Long fansId = getCurrentUser().getFansId();
        return ApiRes.ok(fansService.updates(object, fansId));
    }


}
